package app.auto.runner.base.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import app.auto.runner.base.ActivityStack;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.utility.HandlerUtil;
import app.auto.runner.base.utility.base.Toastial;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Author：何送军
 * creation time：2018/1/12
 **/
public class MyOkhttpUtils {
    private OkHttpClient myOkHttpClient;
    private Request myrequest;
    private static MyOkhttpUtils myOkhttpUtils = new MyOkhttpUtils();

    public MyOkhttpUtils() {

    }

    public static MyOkhttpUtils getMyOkhttpInstance() {
        return myOkhttpUtils;
    }


    public Request okhttpRequestPost(String url, Map map) {
        StringBuffer sb = new StringBuffer();
        for (Object key : map.keySet()) {
            sb.append(key + "=" + map.get(key) + "&");
        }
        final MediaType FORM_CONTENT_TYPE
                = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
        RequestBody requestBody = RequestBody.create(FORM_CONTENT_TYPE, sb.toString());
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return request;

    }

    public Request okhttpRequestGet(String url, Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("?");
        for (Object key : map.keySet()) {
            sb.append(key + "=" + map.get(key) + "&");
        }
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        return request;
    }

    public static Request okhttpRequestPhotoCommon(String Url, String pathName) {
        File file = new File(pathName);
        StringBuffer url = new StringBuffer(Url);
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        RequestBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(String.valueOf(url))
                .post(multipartBody)
                .build();
        return request;

    }
    public static Request okhttpRequestPhoto(String Url, String pathName) {
        File file = new File(pathName);
        StringBuffer url = new StringBuffer(Url);
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        RequestBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("grdid", "APP_IMGUPLOAD")
                .addFormDataPart("sytid", "x")
                .addFormDataPart("fileurl", file.getName())
                .addFormDataPart("data", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(String.valueOf(url))
                .post(multipartBody)
                .build();
        return request;
    }


    public static void upload(String path, String url) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f = new File(path);
        if (f != null) {
            builder.addFormDataPart("img", f.getName(), RequestBody.create(MediaType.parse("image/jpeg"), f));
        }
        //添加其它信息
//        builder.addFormDataPart("time",takePicTime);
//        builder.addFormDataPart("mapX", SharedInfoUtils.getLongitude());
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        MyOkhttpUtils.getMyOkhttpInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                System.out.println("上传照片成功：response = " + response.body().string());


            }
        });
    }


    public OkHttpClient getOkHttpClient() {

        if (myOkHttpClient == null) {
            myOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(new MyInterceptor())
                    .build();
        }
        return myOkHttpClient;
    }

    private static class MyInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.e("", request.url().toString());
            Headers headers = request.headers();
            Log.e("", headers.toString());
            return chain.proceed(request);
        }
    }

    public static boolean fileUpload(final Map params, final String path, final String link) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String BOUNDARY = "---";
                String MULTIPART_FORM_DATA = "Multipart/form-data";
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(link);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
                    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
                    if (params != null && !params.isEmpty()) {
                        StringBuilder sb = new StringBuilder();
                        for (Object e : params.entrySet()) {

                            sb.append(BOUNDARY);
                            sb.append("\r\n");
                            sb.append("Content-Disposition: form-data; name=\"" + ((Map.Entry) e).getKey() + "\"\r\n\r\n");
                            sb.append(((Map.Entry) e).getValue());
                            sb.append("\r\n");
                        }
                        outStream.write(sb.toString().getBytes());
                    }


                    ByteArrayOutputStream out = new ByteArrayOutputStream();

                    BitmapFactory.decodeFile(path).compress(Bitmap.CompressFormat.JPEG, 100, out);

                    try {
                        out.flush();

                        out.close();

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    byte[] buffer = out.toByteArray();

                    byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
                    byte[] content = encode;
                    StringBuilder split = new StringBuilder();
                    split.append(BOUNDARY);
                    split.append("\r\n");
                    split.append("Content-Disposition: form-data;name=\"imgfile\";filename=\"" + path.substring(path.lastIndexOf("\\/")+1) + "\"\r\n");
                    split.append("Content-Type: image/png\r\n");
                    outStream.write(split.toString().getBytes());
                    outStream.write(content, 0, content.length);
                    outStream.write("\r\n".getBytes());
                    byte[] end_data = (BOUNDARY + "--\r\n").getBytes();
                    outStream.write(end_data);
                    outStream.flush();
                            final StringBuffer resultBuffer = new StringBuffer();
                    try {
                        if (conn.getInputStream() != null) {
                            int contentLength = Integer.parseInt(conn.getHeaderField("Content-Length"));
                            if (contentLength > 0) {
                                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                                String temp;
                                while ((temp = br.readLine()) != null) {
                                    resultBuffer.append(temp);
                                }

                            }

                        }
                        HandlerUtil.sendEmptymessage(ActivityStack.publicactivity, new FunCallback() {
                            @Override
                            public void simpleRun(Object o, Object... p) {
                                Toastial.quick(resultBuffer.toString());

                            }
                        });
                        conn.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();

        return false;
    }


//    void upload(String path) {
//
//        try {
//
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//
//            BitmapFactory.decodeFile(path).compress(Bitmap.CompressFormat.PNG, 100, out);
//
//            out.flush();
//
//            out.close();
//
//            byte[] buffer = out.toByteArray();
//
//            byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
//
//            String photo = new String(encode);
//
//            RequestParams params = new RequestParams();
//
//            params.put("photo", photo);
//
//            String url = "http://wyy-pc:8080/tishen/servlet/UploadImgServlet";
//
//            AsyncHttpClient client = new AsyncHttpClient();
//
//            client.post(url, params, new AsyncHttpResponseHandler() {
//
//                @Override
//
//                public void onSuccess(int statusCode, Header[] headers,
//
//                                      byte[] responseBody) {
//
//                    try {
//
//                        if (statusCode == 200) {
//
//                        } else {
//
//
//                        }
//
//                    } catch (Exception e) {
//
//// TODO Auto-generated catch block
//
//                        e.printStackTrace();
//
//                    }
//
//                }
//
//                @Override
//
//                public void onFailure(int statusCode, Header[] headers,
//
//                                      byte[] responseBody, Throwable error) {
//
//
//                }
//
//            });
//
//        } catch (Exception e) {
//
//            e.printStackTrace();
//
//        }
//
//    }

}
